import { _decorator, Collider, Collider2D, Color, Component, Contact2DType, Node, Sprite } from 'cc';
import { CollisionManager } from './CollisionManager';
import { CollisionItem } from './CollisionItem';
const { ccclass, property } = _decorator;

@ccclass('Collision')
export class Collision extends Component {

    @property(Sprite)
    Icon: Sprite = null;

    @property(Collider2D)
    Collider2D: Collider2D = null;

    @property(Color)
    Color: Color = null;

    target: Node = null;


    protected onLoad(): void {
        if (this.Collider2D) {
            this.Collider2D.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
        }
    }

    check(target: Node) {
        if (this.target) {
            const item: CollisionItem = this.target.getComponent(CollisionItem);
            item.removeCollision(this);
        }
        this.target = target;
        const item: CollisionItem = this.target.getComponent(CollisionItem);
        item.addCollision(this);
    }

    changeColor(color: Color = this.Color) {
        this.Icon.color = color;
    }

    braak() {
        this.changeColor();
        this.target = null;
    }


    onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D) {
        if (otherCollider.group == 1 << 3) {
            this.check(otherCollider.node);
            // CollisionManager.Instance.
        }
    }
}


